import { getDict } from "~/utils";
import uploadMedia from "@/components/upload-media";
import { downloadBlob } from "@/utils";
import { mapState } from "vuex";

import {
	downloadPost,
	inspectionList,
	getEditInformation,
	propertyNameList,
	useUnitList,
	getRoomInfo,
	getCheckItemList,
	changeModifyInspectionResults,
	deleteDeleteInspectionResults
} from "../../../api/check-in.js";

export default {
	provide() {
		return {
			initList: this.getListData
		};
	},
	components: { uploadMedia },
	computed: mapState({
		user: state => state.user.user
	}),
	data() {
		return {
			options: [],
			loading: false,
			// states: [],
			rules: {
				roomId: [
					{
						required: true,
						message: "请选择物业名称",
						trigger: "blur"
					}
				],
				projectAddr: [
					{
						required: true,
						message: "请输物业地址",
						trigger: "blur"
					}
				],
				address: [
					{
						required: true,
						message: "请输入具体位置",
						trigger: "blur"
					}
				],
				manageUnit: [
					{
						required: true,
						message: "请选择所属管理所",
						trigger: "change"
					}
				],
				inspectionPerson: [
					{
						required: true,
						message: "请输入巡查人员",
						trigger: "blur"
					},
					{
						min: 1,
						max: 6,
						message: "长度在 1 到 6个字符",
						trigger: "blur"
					}
				],
				inspectionResult: [
					{
						required: true,
						message: "请输入巡查结果",
						trigger: "blur"
					},
					{
						min: 1,
						max: 6,
						message: "长度在 1 到 6个字符",
						trigger: "blur"
					}
				],
				// useUnit: [
				//     {
				//         required: true,
				//         message: "请选择使用单位",
				//         trigger: "change"
				//     }
				// ],
				predictInspectionDate: [
					{
						required: true,
						message: "请选择预计巡查日期",
						trigger: "change"
					}
				],
				inspectionDate: [
					{
						required: true,
						message: "请选择实际巡查日期",
						trigger: "change"
					}
				]
			},
			unitList: [],
			uploadFileList: [], // 选中文件列表
			// 弹出框标题
			title: "新增巡查结果",
			//首页表格勾选列表
			selectDataArr: [],
			//巡查结果详情表单记录
			projectType: "",
			//新增|编辑表单数据
			resultDetailsForm: {
				reportDangerRecord: []
			},
			searchDataFrom: {},
			currentPage: 1,
			inspectionResults: [],
			manageUnits: [],
			// 过滤检索配置
			filterList: [
				{
					label: "物业类型",
					inputType: "dict",
					name: "projectType",
					dictName: "property_types",
					multiple: true
				},
				{
					label: "检查结果",
					inputType: "dict",
					name: "inspectionResult",
					dictName: "inspection_result",
					multiple: true
				},
				{
					label: "管理所",
					inputType: "dict",
					name: "manageUnit",
					dictName: "administrative_office",
					multiple: true
				},
				{
					label: "检查日期",
					inputType: "daterange",
					name: ["startDate", "endDate"]
					// dictName: "inspection_result",
				}
			],
			params: {
				current: 1,
				size: 10,
				propertyName: ""
			},
			//标签页title  （为了展示没什么卵用）
			tabTitle: "上报隐患记录",
			dialogVisible: false,
			pager: {
				total: 0, // 总页数
				currentPage: 1, // 当前页数
				pageSize: 10 // 每页显示多少条
			},
			// 首页列表
			tableData: []
		};
	},
	mounted() {
		this.inspectionResults = getDict("inspection_result");
		this.manageUnits = getDict("administrative_office");
		this.getListData();
	},
	methods: {
		//  * 码值转换
		dictVal_propertyTypes(row, column, cellValue) {
			let obj = getDict("property_types").find(p => p.value == cellValue);
			return obj ? obj.label : "";
		},
		//  * 码值转换
		dictVal_propertyTypes(row, column, cellValue) {
			let obj = getDict("property_types").find(p => p.value == cellValue);
			return obj ? obj.label : "";
		},
		// 菜单点击监听
		handleMenuClick(type) {
			switch (type) {
				case "add":
					this.showDetailsOfInspectionResults("add");
					break;
				case "delete":
					this.handleDelete();
					break;
				case "export":
					this.exportTable();
					break;
			}
		},
		// 管理所格式化
		manageFormatter(row, column, cellValue) {
			const manage = this.manageUnits.find(item => item.value == cellValue);
			return manage.label || "";
		},
		//获取巡查结果列表
		getListData(params = {}) {
			let requestData = { ...this.params, ...params };
			inspectionList(requestData)
				.then(res => {
					const { current, size, total, records } = res.data.data;
					this.tableData = records;
					this.params = requestData;
					this.pager = { total, current, size };
				})
				.catch(() => {});
		},
		//导出
		exportTable() {
			if (this.tableData.length == 0) {
				if (this.params.projectType) {
					this.$message({
						message: " 暂无可导出数据",
						type: "warning"
					});
					return;
				} else if (this.params.inspectionResult) {
					this.$message({
						message: " 暂无可导出数据",
						type: "warning"
					});
					return;
				} else if (this.params.manageUnit) {
					this.$message({
						message: " 暂无可导出数据",
						type: "warning"
					});
					return;
				} else {
					this.$message({
						message: "暂无可导出数据",
						type: "warning"
					});
					return;
				}
			}
			var time = new Date();
			var name =
				time.getFullYear() +
				"-" +
				(time.getMonth() + 1) +
				"-" +
				time.getDate() +
				" " +
				time.getHours() +
				":" +
				time.getMinutes() +
				":" +
				time.getSeconds() +
				"物业巡查结果.xls";
			var url = "/api/inspectionresult/exportInspectionResults";
			let resultIds = this.selectDataArr.map(e => e.resultId);
			let {
				inspectionResult,
				endDate,
				manageUnit,
				propertyName,
				projectType,
				startDate
			} = this.params;
			downloadPost(url, {
				inspectionResult,
				endDate,
				manageUnit,
				propertyName,
				projectType,
				resultIds,
				startDate
			}).then(res => {
				downloadBlob(res.data, name);
			});
		},
		// 删除
		handleDelete() {
			if (this.selectDataArr.length == 0)
				return this.$alert("请勾选要删除的数据！");
			let ids = this.selectDataArr.map(e => e.resultId);
			this.$confirm(`此操作将永久删除该数据, 是否继续?`, {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning"
			})
				.then(() => {
					deleteDeleteInspectionResults(ids)
						.then(res => {
							this.getListData();
							this.$message.success("删除成功");
						})
						.catch(e => {
							this.$message.error("删除失败");
						});
				})
				.catch(() => {
					this.$message.info("已取消删除");
				});
		},
		// 打开新增or编辑表单
		showDetailsOfInspectionResults(v, row) {
			//获取物业名称列表
			row && this.remotePropertyNameMethod(row.propertyName);
			// 表单清空
			this.resultDetailsForm = {
				reportDangerRecord: []
			};
			this.uploadFileList = [];
			// 打开弹窗
			this.dialogVisible = true;
			if (v == "add") {
				this.resultDetailsForm.inspectionPerson = this.user.realName;
				this.title = "新增巡查结果";
				this.$refs.upload &&
					this.$refs.upload.getFiles(this.resultDetailsForm.resultId);
			} else if (v == "edit") {
				this.title = "编辑巡查结果";
				// 获取当前这条巡查结果的详细信息
				getEditInformation(row.resultId)
					.then(res => {
						// 给表单复制
						this.resultDetailsForm = JSON.parse(JSON.stringify(res.data.data));
						this.$nextTick(() => {
							this.$refs.upload &&
								this.$refs.upload.getFiles(this.resultDetailsForm.resultId);
						});
					})
					.catch({});
			}
		},
		keyup(e) {
			this.resultDetailsForm.mobile = e.replace(/[^\d.]/g, "");
		},
		// 物业巡查模糊搜索
		async remotePropertyNameMethod(query) {
			if (query) {
				this.loading = true;
				const res = await propertyNameList(query);
				// this.states = res.data.data;
				this.loading = false;
				this.options = res.data.data.map(item => {
					return { ...item, value: item.roomId, label: item.value };
				});
			} else this.options = [];
		},
		// 使用单位模糊查询
		async remoteUseUnitMethod(query) {
			if (!this.loading) {
				this.loading = true;
				const res = await useUnitList(query);
				this.unitList = res.data.data.map(item => {
					const { value } = item;
					return { value };
				});
			}
			this.loading = false;
		},
		//  物业类型选择监听
		async propertyNameMonitoring(ev) {
			const res = await getRoomInfo(ev);
			this.resultDetailsForm.propertyName = res.data.data.value;
			this.resultDetailsForm.projectAddr = res.data.data.projectAddr;
			this.resultDetailsForm.address = res.data.data.address;
			this.resultDetailsForm.manageUnit = res.data.data.manageUnit;
			this.resultDetailsForm.projectType = res.data.data.projectType;
			//获取检查项列表
			this.getCheckItemList(res.data.data.projectType);
		},
		// 获取检查项列表(新增时请求隐患记录) （参数：物业类型）
		async getCheckItemList(v) {
			const res = await getCheckItemList(v);
			this.$set(this.resultDetailsForm, "reportDangerRecord", res.data.data);
		},
		//关闭弹框
		close() {
			this.$refs.resultDetailsForm.resetFields();
			this.uploadFileList = [];
		},
		// 保存
		save() {
			if (["新增巡查结果", "编辑巡查结果"].includes(this.title)) {
				this.$refs.resultDetailsForm.validate(async valid => {
					if (valid)
						this.$refs.upload.submit(
							"checkin",
							this.resultDetailsForm.resultId
						);
				});
			}
		},
		// 上传文件提交
		async onSuccess(response, file, fileList) {
			let params =
				this.title == "新增巡查结果"
					? { ...this.resultDetailsForm, resultId: response.data }
					: this.resultDetailsForm;
			const res = await changeModifyInspectionResults(params, this.title);

			// if (res.data.data.data == 200) {
			this.dialogVisible = false;
			this.$message({
				message: res.data.data.msg,
				type: "success"
			});
			this.getListData();
			// }
		}
	}
};
